<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/12
 * Time: 16:15
 */

namespace app\admin\controller;


use app\admin\model\FoodsSpec;
use app\admin\model\MemberUser;
use app\admin\model\ShopCategory;
use app\admin\model\ShopFoods;
use app\admin\model\ShopList;
use app\admin\model\Temporary;
use app\index\model\FoodAttribute;
use think\facade\Session;

class FoodsController extends BaseController
{


    public function categoryList(){
        $shop_id = Session::get('shop_id')?['shop_id'=>Session::get('shop_id')]:"";
        $data['list'] = ShopCategory::where($shop_id)->paginate(10,false)->each(function ($item){
            $item->shop = ShopList::where('id',$item->shop_id)->field('id,shop_name')->find();
        });
        $this->assign('data',$data);
        return $this->fetch();
    }
    public function categoryAdd(){
        $id = (int)input('get.id');
        $shop_id = Session::get('shop_id')?['id'=>Session::get('shop_id')]:"";
        $shop = Session::get('shop_id')?['shop_id'=>Session::get('shop_id')]:"";
        if (request()->isPost()){
            $data = input('post.');
            if ($data['spike'] == 1){
                $spike = ShopCategory::where($shop)->where('spike',1)->find();
                if ($spike){
                    return json(['code'=>0,'msg'=>'秒杀分类已存在']);
                }
            }
            $filed = ShopCategory::where($shop_id)->where('category_name',$data['category_name'])->find();
            if ($filed){
                return json(['code'=>0,'msg'=>'分类名已存在']);
            }
            $ret = ShopCategory::name('shop_category')->insert($data);
            if (!$ret){
                return json(['code'=>0,'msg'=>'保存失败']);
            }
            return json(['code'=>1,'msg'=>'保存成功']);
        }
        $data['info'] = ShopCategory::where('id',$id)->find();
        $data['list'] = ShopList::where($shop_id)->field('id,shop_name')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function categoryEdit(){
        $category_id = input('get.id');
        if (request()->isPost()){
            $post = input('post.');
            if ($post['spike'] == 1){
                $spike = ShopCategory::where('shop_id',$post['shop_id'])->where('spike',1)->find();
                if ($spike && $spike['id'] != $post['id']){
                    return json(['code'=>0,'msg'=>'秒杀分类已存在']);
                }
            }
            $upData = [
                'introduce'=>$post['introduce'],
                'sort'=>$post['sort'],
                'discount'=>$post['discount'],
                'spike'=>$post['spike'],
                'status'=>$post['status'],
            ];
            $ret = ShopCategory::where('id',$post['id'])->update($upData);
            if (!$ret){
                return json(['code'=>0,'msg'=>'保存失败']);
            }
            return json(['code'=>1,'msg'=>'保存成功']);
        }
        $data['info'] = ShopCategory::where('id',$category_id)->find()->toArray();
        $data['info']['shop_id'] = ShopList::where('id',$data['info']['shop_id'])
            ->field('id,shop_name')->find()->toArray();
        $this->assign('data',$data);
        return $this->fetch();
    }
    public function categoryDel(){
        $data = input('post.id');
        $list = $this->del('shop_category','id',$data);
        if ($list){
            return json(['code'=>1,'msg'=>'删除成功']);
        }else{
            return json(['code'=>0,'msg'=>'删除失败']);
        }
    }

    public function foodsList(){
        return $this->fetch();
    }
    public function foodsData($page,$limit){
        $shop_id = Session::get('shop_id')?['shop_id'=>Session::get('shop_id')]:"";
        $where = input('param.food_name')?[['food_name','like','%'.input('param.food_name').'%']]:'';
        $data = ShopFoods::where($shop_id)->where($where)
            ->where('spike_status',0)->page($page,$limit)->select()->each(function ($item){
            $shop = ShopList::where('id',$item->shop_id)->value('shop_name');
            if ($shop){
                $item->shop_id = $shop;
            }else{
                $item->shop_id = '';
            }
            $category = ShopCategory::where('id',$item->category_id)->value('category_name');
            if ($category){
                $item->category_id = $category;
            }else{
                $item->category_id = '';
            }
            $item->cook_id = MemberUser::where('id',$item->cook_id)->value('true_name');
        })->toArray();
        $count = ShopFoods::where($shop_id)->where($where)->count();
        $res = [
            'code'=>0,
            'msg'=>'返回成功',
            'count'=>$count,
            'data'=>$data
        ];
        return json($res);
    }
    public function foodsAdd(){
        $shop_id =Session::get('shop_id');
        if ($shop_id){
            $data['shop'] = ShopList::where('id',$shop_id)->field('id,shop_name')->select()->toArray();
            $data['category'] = ShopCategory::where('shop_id',$shop_id)->field('id,category_name')
                ->where('status',1)->where('spike',2)->select()->toArray();
            $this->assign('data',$data);
            $data['food'] = ShopFoods::where('fu_id',0)
                ->field('id,food_name')->select()->toArray();
//            dump($data);die();
            $this->assign('data',$data);
            return $this->fetch();
        }else{
            $data['cook'] = MemberUser::where('status',3)->where('staff_status',1)
                ->field('id,true_name')->select()->toArray();
            $this->assign('data',$data);
            return $this->fetch('fu_add');
        }
    }
    public function foodData(){
        $food_id = input('post.id');
        $data['food'] = ShopFoods::where('id',$food_id)
            ->field('id,food_name,introduce,image,images,price,cook_id,status')->find()->toArray();
        $data['food']['images'] = explode(',',$data['food']['images']);
        $data['spec'] = FoodsSpec::with('shopAttribute')
            ->where('food_id',$data['food']['id'])->select()->toArray();
        $data['cook'] = MemberUser::where('id',$data['food']['cook_id'])->field('id,true_name')->select()->toArray();
        return json($data);
    }
    public function foodsEdit(){
        $shop_id =Session::get('shop_id');
        $food_id =input('get.id');
        if ($shop_id){
            $data['food'] = ShopFoods::where('id',$food_id)
                ->field('id,shop_id,category_id,food_name,introduce,image,images,price,cook_id,status')
                ->find()->toArray();
            $data['food']['images'] = explode(',',$data['food']['images']);
            $data['food']['shop_id'] = ShopList::where('id',$data['food']['shop_id'])
                ->field('id,shop_name')->select()->toArray();
            $data['food']['category_id'] = ShopCategory::where('id',$data['food']['category_id'])
                ->field('id,category_name')->select()->toArray();
            $data['spec'] = FoodsSpec::with('shopAttribute')
                ->where('food_id',$data['food']['id'])->select()->toArray();
            $data['cook'] = MemberUser::where('status',3)->field('id,true_name')->select()->toArray();
            $this->assign('data',$data);
            return $this->fetch();
        }else{
            $data['food'] = ShopFoods::where('id',$food_id)
                ->field('id,food_name,introduce,image,images,price,cook_id,status')->find()->toArray();
            $data['food']['images'] = explode(',',$data['food']['images']);
            $data['spec'] = FoodsSpec::with('shopAttribute')
                ->where('food_id',$data['food']['id'])->select()->toArray();
            $data['cook'] = MemberUser::where('status',3)->field('id,true_name')->select()->toArray();
            $this->assign('data',$data);
//            dump($data);die();
            return $this->fetch('fu_edit');
        }
    }

    public function foodEditSave(){
        $data = input('post.');
        $specDel = FoodsSpec::with(['shopAttribute'=>function($query){
            $query->field('id,spec_id');
        }])->where('food_id',$data['food_id'])->select()->toArray();
        $spec_id = [];
        $attribute = [];
        foreach ($specDel as $k=>$v){
            $spec_id[] =$v['id'];
            foreach ($v['shop_attribute'] as $key=>$value){
                $attribute[] = $value['id'];
            }
        }
        FoodsSpec::destroy(['id'=>$spec_id]);
        FoodAttribute::destroy(['id'=>$attribute]);
        $shop_id = Session::get('shop_id');
        if ($shop_id){
            $foods = [
                'shop_id'=>$data['shop_id'],
                'category_id'=>$data['category_id'],
                'introduce'=>$data['introduce'],
                'image'=>$data['foods_image'],
                'images'=>implode(',',$data['foods_images']),
                'price'=>$data['price'],
                'cook_id'=>$data['cook_id'],
                'status'=>$data['status'],
            ];
        }else{
            $foods = [
                'introduce'=>$data['introduce'],
                'image'=>$data['foods_image'],
                'images'=>implode(',',$data['foods_images']),
                'price'=>$data['price'],
                'cook_id'=>$data['cook_id'],
                'status'=>$data['status'],
            ];
        }
        $foods_id = ShopFoods::update($foods,['id'=>$data['food_id']]);
        if(array_key_exists('spec_name',$data)){
            $spec = [];
            for ($i=0,$item=count($data['spec_name']);$i<$item;$i++){
                $spec[$i]['spec_name'] = $data['spec_name'][$i];
                $spec[$i]['spec_key'] = $data['spec_key'][$i];
                $spec[$i]['spec_id'] = FoodsSpec::insertGetId(['food_id'=>$data['food_id'],'spec_name'=>$data['spec_name'][$i]]);
            }
            $value = [];
            for ($i=0,$item=count($data['spec_value']);$i<$item;$i++){
                $value[$i]['spec_value'] = $data['spec_value'][$i];
                $value[$i]['spec_price'] = $data['spec_price'][$i];
                $value[$i]['spec_key'] = $data['spec_key1'][$i];
            }
            for ($i=0,$item=count($spec);$i<$item;$i++){
                for ($j=0,$items=count($value);$j<$items;$j++){
                    if ($spec[$i]['spec_key'] == $value[$j]['spec_key']){
                        $ins= [
                            'spec_id'=>$spec[$i]['spec_id'],
                            'attribute_name'=>$value[$j]['spec_value'],
                            'price'=>$value[$j]['spec_price'],
                        ];
                        FoodAttribute::insert($ins);
                    }
                }
            }
        }
        if ($foods_id){
            return json(['code'=>1,'msg'=>'保存成功']);
        }
        return json(['code'=>0,'msg'=>'保存失败']);
    }

    public function foodSave(){
        $data = input('post.');
        $shop_id = Session::get('shop_id');
        if ($shop_id){
            $foods = [
                'shop_id'=>$data['shop_id'],
                'category_id'=>$data['category_id'],
                'spare_id'=>$data['category_id'],
                'fu_id'=>$data['fu_id'],
                'food_name'=>$data['food_name'],
                'introduce'=>$data['introduce'],
                'image'=>$data['foods_image'],
                'images'=>implode(',',$data['foods_images']),
                'price'=>$data['price'],
                'cook_id'=>$data['cook_id'],
                'status'=>$data['status'],
            ];
            $repeat = ShopFoods::where('shop_id',$data['shop_id'])->where('fu_id',$data['fu_id'])->find();
            if ($repeat){
                return json(['code'=>0,'msg'=>'这道菜已加入本店']);
            }
        }else{
            $foods = [
                'food_name'=>$data['food_name'],
                'fu_id'=>0,
                'introduce'=>$data['introduce'],
                'image'=>$data['foods_image'],
                'images'=>implode(',',$data['foods_images']),
                'price'=>$data['price'],
                'cook_id'=>$data['cook_id'],
                'status'=>$data['status'],
            ];
        }
        $foods_id = ShopFoods::insertGetId($foods);
        if(array_key_exists('spec_name',$data)){
        	$spec = [];
	        for ($i=0,$item=count($data['spec_name']);$i<$item;$i++){
	                $spec[$i]['spec_name'] = $data['spec_name'][$i];
	                $spec[$i]['spec_key'] = $data['spec_key'][$i];
	                $spec[$i]['spec_id'] = FoodsSpec::insertGetId(['food_id'=>$foods_id,'spec_name'=>$data['spec_name'][$i]]);
	        }
	        $value = [];
	        for ($i=0,$item=count($data['spec_value']);$i<$item;$i++){
	            $value[$i]['spec_value'] = $data['spec_value'][$i];
	            $value[$i]['spec_price'] = $data['spec_price'][$i];
	            $value[$i]['spec_key'] = $data['spec_key1'][$i];
	        }
	        for ($i=0,$item=count($spec);$i<$item;$i++){
	            for ($j=0,$items=count($value);$j<$items;$j++){
	                if ($spec[$i]['spec_key'] == $value[$j]['spec_key']){
	                    $ins= [
	                        'spec_id'=>$spec[$i]['spec_id'],
	                        'attribute_name'=>$value[$j]['spec_value'],
	                        'price'=>$value[$j]['spec_price'],
	                    ];
	                    FoodAttribute::insert($ins);
	                }
	            }
	        }
        }
        if ($foods_id){
            return json(['code'=>1,'msg'=>'保存成功']);
        }
        return json(['code'=>0,'msg'=>'保存失败']);
    }

    public function foodDel(){
        $food = input('post.id');
        $specDel = FoodsSpec::with(['shopAttribute'=>function($query){
            $query->field('id,spec_id');
        }])->where('food_id',$food)->select()->toArray();
        $spec_id = [];
        $attribute = [];
        foreach ($specDel as $k=>$v){
            $spec_id[] =$v['id'];
            foreach ($v['shop_attribute'] as $key=>$value){
                $attribute[] = $value['id'];
            }
        }
        FoodsSpec::destroy(['id'=>$spec_id]);
        FoodAttribute::destroy(['id'=>$attribute]);
        $ret = ShopFoods::destroy(['id'=>$food]);
        if (!$ret){
            return json(['code'=>0,'msg'=>'删除失败']);
        }
        return json(['code'=>1,'msg'=>'删除成功']);
    }

    //临时菜品列表
    public function temporary(){
        return $this->fetch();
    }

    public function temporaryData($page,$limit){
        $shop_id = Session::get('shop_id')?['shop_id'=>Session::get('shop_id')]:"";
        $where = input('param.food_name')?[['food_name','like','%'.input('param.food_name').'%']]:'';
        $data = Temporary::with(['shop'=>function($query){
            $query->field('id,shop_name');
        }])->where($shop_id)->where($where)->page($page,$limit)->select()->each(function ($item){
            $item->shop_id = $item->shop->shop_name;
        })->toArray();
        $count = Temporary::where($shop_id)->where($where)->count();
        $res = [
            'code'=>0,
            'msg'=>'返回成功',
            'count'=>$count,
            'data'=>$data
        ];
        return json($res);
    }

    public function temporaryAdd(){
        if (request()->isPost()){
            $post = input('post.');
            $where = Temporary::where('shop_id',$post['shop_id'])
                ->where('food_name',trim($post['food_name']))->find();
            if ($where){
                return json(['code'=>0,'msg'=>'菜名已存在']);
            }
            $ret = Temporary::create($post);
            if (!$ret){
                return json(['code'=>0,'msg'=>'保存失败']);
            }
            return json(['code'=>1,'msg'=>'保存成功']);
        }
        $shop_id = Session::get('shop_id')?['id'=>Session::get('shop_id')]:'';
        $data['list'] = ShopList::where($shop_id)->field('id,shop_name')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function temporaryEdit(){
        if (request()->isPost()){
            $post = input('post.');
            $data = [
                'food_name'=>$post['food_name'],
                'shop_id'=>$post['shop_id'],
                'price'=>$post['price'],
                'status'=>$post['status'],
            ];
            $ret = Temporary::update($data,['id'=>$post['id']]);
            if (!$ret){
                return json(['code'=>0,'msg'=>'保存失败']);
            }
            return json(['code'=>1,'msg'=>'保存成功']);
        }
        $id = input('get.id');
        $shop_id = Session::get('shop_id')?['id'=>Session::get('shop_id')]:'';
        $data['list'] = ShopList::where($shop_id)->field('id,shop_name')->select();
        $data['info'] = Temporary::where('id',$id)->find();
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function temporaryDel(){
        $id = (int)input('post.id');
        $ret = Temporary::destroy($id);
        if (!$ret){
            return json(['code'=>0,'msg'=>'删除失败']);
        }
        return json(['code'=>1,'msg'=>'删除成功']);
    }
}